package timbap.artwork.retrieval;

import java.io.InputStream;

public class ImageRetrieverThread extends Thread {

    private String imageUrl;
    private ImageResultHandler resultHandler;
    private ArtworkRetriever artworkRetriever;
    private boolean done = false;

    public ImageRetrieverThread(final String pImageUrl,
                                final ImageResultHandler pResultHandler,
                                final ArtworkRetriever pArtworkRetriever) {
        imageUrl = pImageUrl;
        resultHandler = pResultHandler;
        artworkRetriever = pArtworkRetriever;
    }

    protected void publishResult(final InputStream pImageDataFromHttp) {
        done = true;
        resultHandler.imageResultFound(pImageDataFromHttp);
    }

    protected void publishRetrievalFailed() {
        done = true;
        resultHandler.imageRetrievalFailed();
    }

    public boolean isDone() {
        return done;
    }

    @Override
    public void run() {
        try {
            InputStream tImageDataFromHttp = artworkRetriever.retrieveImageFromUrl(imageUrl);
            if (tImageDataFromHttp != null && tImageDataFromHttp.available() > 0) {
                publishResult(tImageDataFromHttp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        publishRetrievalFailed();
    }
}
